import React, { useState, useEffect } from 'react';
import { Button } from 'antd';
import { captcha1 } from '../../../api/csy/api'
import '../css/login/face.less'

// 定义 FushuActionCaptcha 类型
declare global {
    interface Window {
        FushuActionCaptcha: any; // 引入 FushuActionCaptcha 类型
    }
}

interface CaptchaComponentProps {
    onCaptchaSuccess?: (captchaRes: any) => void; // 改为可选属性
}

interface YzmcodeProps {
    onCaptchaSuccess?: (captchaRes: any) => void;
}

const CAPTCHA_APP_ID = '192076471';
const SLIDER_CAPTCHA_JS = 'https://captcha.api.hi.cn/captcha.js';

// 添加全局变量来跟踪脚本加载状态
let scriptLoaded = false;

const CaptchaComponent: React.FC<CaptchaComponentProps> = ({ onCaptchaSuccess }) => {
    const [captcha, setCaptcha] = useState<null | any>(null);
    const [isshow, setIsshow] = useState(false);

    useEffect(() => {
        // 如果脚本已经加载，直接创建实例
        if (scriptLoaded && window.FushuActionCaptcha) {
            const newCaptcha = new window.FushuActionCaptcha(CAPTCHA_APP_ID, callback, {});
            setCaptcha(newCaptcha);
            return;
        }

        // 动态加载 CAPTCHA 脚本
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = SLIDER_CAPTCHA_JS;

        script.onload = () => {
            console.log('Captcha JS 加载成功');
            scriptLoaded = true;
            // 在脚本加载成功后，创建 captcha 实例
            const newCaptcha = new window.FushuActionCaptcha(CAPTCHA_APP_ID, callback, {});
            setCaptcha(newCaptcha);
        };

        document.head.appendChild(script);

        return () => {
            // 不再移除脚本，因为其他组件可能还需要使用
            if (captcha) {
                captcha.destroy && captcha.destroy();
            }
        };
    }, []);

    const openCaptcha = () => {
        // 如果 captcha 实例存在，则显示验证码
        if (captcha) {
            captcha.show();
        } else {
            console.log('验证码实例未创建');
        }
    };

    const callback = (captchaRes: any) => {
        if (captchaRes.ret === 0) {
            console.log('验证码验证成功');
            setIsshow(true); // 显示"验证成功"按钮
            captcha1(); // 调用 captcha1 函数，可能是发送请求
            if (onCaptchaSuccess) {
                onCaptchaSuccess(captchaRes); // 调用成功回调
            }
        } else {
            console.log('验证码验证失败');
        }
    };

    return (
        <div>
            {isshow && <Button>验证成功</Button>}
            {!isshow && (
                <div>
                    <Button onClick={openCaptcha}>验证滑块</Button>
                </div>
            )}
        </div>
    );
};

 
export default CaptchaComponent;
